package info.leetcode.answer.Array.TwoDimensionalArray.change;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 生命游戏
 * @date 2024/3/1 14:10
 */
public class GameOfLife {
    public static void main(String[] args) {
        int[][] board = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
        board = gameOfLife(board);
        System.out.println(board);
    }

    private static int[][] gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                int result = 0;
                for (int k = -1; k < 2; k++) {
                    if (i + k < 0 || i + k == board.length) {
                        continue;
                    }
                    for (int l = -1; l < 2; l++) {
                        if (k == 0 && l == 0) {
                            continue;
                        }
                        if (j + l < 0 || j + l == board[i + k].length) {
                            continue;
                        }
                        int transvers = i + k;
                        int direction = j + l;
                        if (board[transvers][direction] % 2 == 1) {
                            result++;
                        }
                    }
                }
                    if ((result < 2||result >3) &&  board[i][j]  ==1 ){
                        board[i][j] = 3;
                    }
                    if (board[i][j] == 0 && result ==3){
                        board[i][j] = 2;
                    }

            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == 2) {
                    board[i][j] = 1;
                }
                if (board[i][j] == 3) {
                    board[i][j] = 0;
                }
            }
        }


        return board;
    }
}
